const { db } = require('../config/database');

class Event {
  // 创建事件
  static create(user_id, type, data) {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('INSERT INTO events (user_id, type, data) VALUES (?, ?, ?)');
      stmt.run(user_id, type, data, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({
            id: this.lastID,
            user_id,
            type,
            data
          });
        }
      });
      stmt.finalize();
    });
  }

  // 根据用户ID查找事件
  static findByUserId(user_id) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM events WHERE user_id = ? ORDER BY triggered_at DESC', [user_id], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }

  // 根据类型和用户ID查找事件
  static findByTypeAndUser(type, user_id) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM events WHERE type = ? AND user_id = ? ORDER BY triggered_at DESC', [type, user_id], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }
}

module.exports = Event;